import React, { useEffect, useState, useRef } from 'react';
import moment from 'moment';
import cn from 'classnames';
import { history } from 'umi'
import { formatMessage } from 'umi';
import { DatePicker, Empty, Modal, Tooltip, message, Dropdown, Menu, Icon, Button, Divider } from 'antd';

import DateFormatter from '@/components/DateFormatter';
import authHelper from '@/utils/auth/helper';
import If from '@/components/If';
import { isSuccess } from '@/utils/request';

import styles from '@/pages/SalaryManage/SalaryCalculate/TemplateSetting/index.less';
import { deleteSalaryItem } from '@/services/salaryManage/salaryCalculate';
import { goToSalarymainadd, goToProcessDetail } from '@/pages/SalaryManage/utils/pageNavigateUtil';
import salaryManageStyle from '@/pages/SalaryManage/salaryManage.less';
import { obtainDictMap } from '@/pages/SalaryManage/utils';
import tabMessageUtil from '@/pages/SalaryManage/utils/tabMessageUtil';
import StatusTag from '@/pages/SalaryManage/components/ProcessStatus';
import { SalaryTemplateModal } from '@/pages/SalaryManage/SalaryCalculate/TemplateSetting/SalaryTemplateEdit/components/SalaryTemplateModal';

const { confirm } = Modal;

const SALARY_OBJECT_OPTIONS = 'salaryObjectOptions';
const DICT_NAME_LIST = [SALARY_OBJECT_OPTIONS];

// 跳转到引入模板页
const goToTemplateLibrary = (monthData, currentOrgCode, currentSelectYear) => {
    const pathname = '/finance/salary/calculate/quoteTemplateLibrary';
    const query = {
        ...(monthData.salaryTemplateId ? { targetid: monthData.salaryTemplateId } : {}),
        targetcode: currentOrgCode,
        year: currentSelectYear,
        month: monthData.month
    };

    tabMessageUtil.memoFromTo(pathname, query);
    history.push({
        pathname,
        query,
        state: {
            tabRoute: true,
            tabRefresh: true
        }
    });
};

const gotoSalaryMainAdd = (organizationCode, item, itemType, disabled) => {
    goToSalarymainadd({ query: { organizationCode, itemType, id: item.id, disabled } }, disabled ? 'detail' : 'edit');
};

// 引导页第2页
const step2Tip = `<div style="width:350px; white-space: initial">
    <div>薪资要素还未配置哦~</div>
    <div>
        请点击
        【<i class="iconfont iconlsit_goto-icon"></i>引用模板】或
        【<i class="iconfont iconlistfunction_edit_icon_default iconfont-larger"></i>编辑】进行配置
    </div>
</div>`;

/**
 * 展示选择时间
 */
const showMonthTimePicker = (year, month, selectedDate, afterChange = () => {}, monthData) => {
    const valueStore = { date: selectedDate };

    const Picker = ({ beginDate, endDate, currDate }) => {
        const [value, setValue] = useState(currDate);

        return (
            <div>
                生成薪资条日期：
                <DatePicker
                    placeholder="请选择"
                    disabledDate={currentDate =>
                        currentDate.isBefore(beginDate, 'day') || currentDate.isAfter(endDate, 'day')
                    }
                    defaultPickerValue={moment(beginDate)}
                    showToday={false}
                    value={value}
                    onChange={val => {
                        setValue(val);
                        valueStore.date = val;
                    }}
                    dropdownClassName={salaryManageStyle.pickerMonthSame}
                />
            </div>
        );
    };

    const beginDate = moment(monthData.generateStartDate);
    const endDate = moment(monthData.generateEndDate);

    confirm({
        title: '编辑日期',
        content: <Picker beginDate={beginDate} endDate={endDate} currDate={selectedDate} />,
        cancelText: '取消',
        okText: '确认',
        onOk() {
            if (!valueStore.date) {
                message.warn('请选择时间');
            }
            console.log('选择的时间是：', valueStore.date?.format('YYYY-MM-DD'));
            afterChange(valueStore.date, monthData);
        }
    });
};

const SalaryItemList = React.memo(
    ({ data = [], disabled = false, itemType, organizationCode, afterDel, templateId, month }) => {
        const [salaryObjectEnum, setSalaryObjectEnum] = useState({});

        useEffect(() => {
            obtainDictMap(DICT_NAME_LIST).then(enumMap => {
                setSalaryObjectEnum(enumMap[SALARY_OBJECT_OPTIONS]);
            });
        }, []);

        /**
         * 删除薪资项
         * @param item 薪资项
         */
        const delSalaryItem = item => {
            Modal.confirm({
                title: '确认',
                content: `确定要删除【${month}月】的【${item.parentTitle}${item.title}】吗？`,
                onCancel() {},
                onOk() {
                    deleteSalaryItem({ templateId, salaryItemId: item.id }).then(response => {
                        if (isSuccess(response)) {
                            message.success(response.msg);
                            afterDel();
                        } else {
                            message.error(response.msg);
                        }
                    });
                }
            });
        };

        return (
            <div className={styles.salaryItemList}>
                {data.map(item => (
                    <Dropdown
                        key={item.id}
                        trigger={['hover']}
                        getPopupContainer={triggerNode => triggerNode.parentNode}
                        overlay={() => (
                            <Menu className={styles.dropdownBox}>
                                <Menu.Item className={styles.dropdownItem}>
                                    <span className={styles.dropdownLabel}>全称：</span>
                                    <span>
                                        {item.parentTitle}
                                        {item.title}
                                    </span>
                                </Menu.Item>
                                <Menu.Item className={styles.dropdownItem}>
                                    <span className={styles.dropdownLabel}>
                                        {(item.formulaFlow && '审批流：') ||
                                            (item.formulaFunc && '公式：') ||
                                            (item.staffInfoName && '取值关联字段：')}
                                    </span>
                                    <span>{item.formulaFlow || item.formulaFunc || item.staffInfoName}</span>
                                </Menu.Item>
                                <Menu.Item className={styles.dropdownItem}>
                                    <span className={styles.dropdownLabel}>对象：</span>
                                    <span>{salaryObjectEnum[item.salaryObject]}</span>
                                </Menu.Item>
                            </Menu>
                        )}
                        placement="topCenter"
                        mouseEnterDelay={0.3}
                    >
                        <div className={styles.salaryItemLabelWrap}>
                            <span className={styles.salaryItemLabel}>{item.parentTitle}</span>
                            <span className={styles.salaryItemLabel}>{item.title}</span>
                            <If condition={!disabled}>
                                <Icon type="close" className={styles.delIcon} onClick={() => delSalaryItem(item)} />
                            </If>
                            <div
                                className={styles.salaryItemLabelBtnWrap}
                                onClick={() => gotoSalaryMainAdd(organizationCode, item, itemType, disabled)}
                            />
                        </div>
                    </Dropdown>
                ))}
            </div>
        );
    }
);

const MonthSalaryMain = ({
    monthSalaryList = [],
    currentSelectYear,
    currentSelectMonth,
    currentOrgCode,
    afterChangeGenerateDate,
    simplePageVo = {},
    afterEdit = () => {}
}) => {
    const [editModalVisible, setEditModalVisible] = useState(false);
    const editRef = useRef(null);

    const onEdit = monthData => {
        editRef.current = {
            currentYear: currentSelectYear,
            currentMonth: monthData.month,
            templateId: monthData.salaryTemplateId,
            organizationCode: currentOrgCode
        };
        setEditModalVisible(true);
    };

    return (
        <div className={styles.salaryContent} id="monthSalaryMain">
            <div className={styles.titleWrap}>
                <div className={styles.leftTitleWrap}>
                    <div className={styles.title}>
                        {/* 月模板配置 */ formatMessage({ id: 'templateSetting.salaryTemplate.salaryMainSetTitle' })}
                        <StatusTag templateInfo={simplePageVo} />
                    </div>
                </div>
                <div className={styles.rightTitleWrap}>
                    <Button
                        type="link"
                        onClick={() =>
                            goToProcessDetail({
                                processDefinitionId: simplePageVo.processDefinitionId,
                                processInstanceId: simplePageVo.processInstanceId
                            })
                        }
                        className={styles.linkBtn}
                        disabled={!simplePageVo.approveDetailAble}
                    >
                        查看审批详情
                    </Button>
                    <If
                        condition={authHelper.checkCode('finance:salary:computation:setting:salarytemp:importmulttemp')}
                    >
                        <Divider type="vertical" />
                        <Button
                            type="link"
                            onClick={() => {
                                goToTemplateLibrary({ month: currentSelectMonth }, currentOrgCode, currentSelectYear);
                            }}
                            className={styles.linkBtn}
                            disabled={simplePageVo.disable}
                        >
                            <i
                                className="icon iconfont iconmobanpeizhi"
                                style={{
                                    fontSize: 12,
                                    color: simplePageVo.disable ? 'rgba(0, 0, 0, 0.25)' : '#FFA22D',
                                    lineHeight: '21px',
                                    marginRight: '6px'
                                }}
                            />
                            {/* 引入多个模板 */ formatMessage({ id: 'templateSetting.salaryTemplate.useMoreTemplate' })}
                        </Button>
                        <Tooltip title="引入的多个模版，将会直接覆盖当前配置的对应月份">
                            <Icon type="question-circle" style={{ marginLeft: '5px', opacity: 0.65 }} />
                        </Tooltip>
                    </If>
                </div>
            </div>
            <div className={styles.salaryMonthWrap}>
                {monthSalaryList.map((monthData, index) => (
                    <div
                        id={`monthSalaryMain-${monthData.month}`}
                        className={styles.salaryMonthDetailWrap}
                        key={monthData.salaryTemplateId}
                        tabIndex={-1}
                    >
                        <div className={styles.monthHeader}>
                            <div className={styles.monthName}>
                                {monthData.name}
                                {monthData.tips ? (
                                    <Tooltip title={monthData.tips}>
                                        <Icon
                                            type="question-circle"
                                            style={{
                                                marginLeft: '5px',
                                                fontSize: '14px',
                                                lineHeight: '21px',
                                                opacity: 0.65
                                            }}
                                        />
                                    </Tooltip>
                                ) : null}
                                <Button
                                    className={cn(salaryManageStyle.iconBtn, styles.monthTimePicker)}
                                    onClick={() =>
                                        showMonthTimePicker(
                                            currentSelectYear,
                                            monthData.month,
                                            monthData.generateDate ? moment(monthData.generateDate) : null,
                                            afterChangeGenerateDate,
                                            monthData
                                        )
                                    }
                                    disabled={simplePageVo.disable || monthData.disable}
                                >
                                    <span className="pg-picker">
                                        <i className={cn(['iconfont', 'iconoa_menu_icon_attendance'])} />
                                        <span className="pg-time">
                                            <DateFormatter
                                                value={monthData.generateDate}
                                                pattern="MM-DD"
                                                emptyMessage="MM-DD"
                                            />
                                        </span>
                                    </span>
                                    <span>生成薪资条</span>
                                </Button>
                            </div>
                            <div
                                {...(index === 0
                                    ? { 'data-step': 2, 'data-intro': step2Tip, 'data-position': 'top' }
                                    : {})}
                                className={styles.monthOperation}
                            >
                                <If
                                    condition={authHelper.checkCode(
                                        'finance:salary:computation:setting:salarytemp:importonetemp'
                                    )}
                                >
                                    {/* 引入模板 */}
                                    <Tooltip
                                        title={formatMessage({ id: 'templateSetting.salaryTemplate.useTemplate' })}
                                    >
                                        <Button
                                            className={cn(salaryManageStyle.iconBtn)}
                                            disabled={simplePageVo.disable || monthData.disable}
                                            onClick={() =>
                                                goToTemplateLibrary(monthData, currentOrgCode, currentSelectYear)
                                            }
                                        >
                                            <i className={cn('iconfont', 'iconlsit_goto-icon', styles.iconBtn)} />
                                        </Button>
                                    </Tooltip>
                                </If>

                                {/* 编辑 */}
                                <If
                                    condition={authHelper.checkCode(
                                        'finance:salary:computation:setting:salarytemp:edittemp'
                                    )}
                                >
                                    <Tooltip title={formatMessage({ id: 'templateSetting.salaryTemplate.edit' })}>
                                        <Button
                                            className={cn(salaryManageStyle.iconBtn)}
                                            disabled={simplePageVo.disable || monthData.disable}
                                            onClick={() => onEdit(monthData, currentOrgCode, currentSelectYear)}
                                        >
                                            <i
                                                className={cn(
                                                    'iconfont',
                                                    'iconlistfunction_edit_icon_default',
                                                    styles.iconBtn,
                                                    styles.iconBtnLarger
                                                )}
                                            />
                                        </Button>
                                    </Tooltip>
                                </If>
                            </div>
                        </div>
                        {(monthData.usedAddSalaryItems && monthData.usedAddSalaryItems.length) ||
                        (monthData.usedLessSalaryItems && monthData.usedLessSalaryItems.length) ? (
                            <div className={styles.monthContent}>
                                <div>
                                    <div className={styles.itemTitle}>
                                        <i
                                            className="icon iconfont iconsalary_add_icon"
                                            style={{
                                                fontSize: 14,
                                                color: 'rgba(79, 216, 123, 1)'
                                            }}
                                        />
                                        <span className={styles.itemTitleText}>
                                            {/* 薪资加项 */ formatMessage({
                                                id: 'templateSetting.salaryTemplate.salaryAddItem'
                                            })}
                                        </span>
                                    </div>
                                    <SalaryItemList
                                        data={monthData.usedAddSalaryItems || []}
                                        disabled={simplePageVo.disable || monthData.disable}
                                        itemType="add"
                                        organizationCode={currentOrgCode}
                                        afterDel={afterEdit}
                                        templateId={monthData.salaryTemplateId}
                                        month={monthData.month}
                                    />
                                </div>
                                <div>
                                    <div className={styles.itemTitle}>
                                        <i
                                            className="icon iconfont iconsalary_minus_icon"
                                            style={{
                                                fontSize: 14,
                                                color: 'rgba(255, 121, 67, 1)'
                                            }}
                                        />
                                        <span className={styles.itemTitleText}>
                                            {/* 薪资减项 */ formatMessage({
                                                id: 'templateSetting.salaryTemplate.salaryReduceItem'
                                            })}
                                        </span>
                                    </div>
                                    <SalaryItemList
                                        data={monthData.usedLessSalaryItems || []}
                                        disabled={simplePageVo.disable || monthData.disable}
                                        itemType="reduce"
                                        organizationCode={currentOrgCode}
                                        afterDel={afterEdit}
                                        templateId={monthData.salaryTemplateId}
                                        month={monthData.month}
                                    />
                                </div>
                            </div>
                        ) : (
                            <Empty
                                className={styles.monthEmpty}
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                description={
                                    <span style={{ display: 'block' }}>
                                        <span style={{ display: 'block' }}>本月薪资还未配置哦 ~ </span>
                                        <If
                                            condition={
                                                authHelper.checkCode(
                                                    'finance:salary:computation:setting:salarytemp:importonetemp'
                                                ) ||
                                                authHelper.checkCode(
                                                    'finance:salary:computation:setting:salarytemp:edittemp'
                                                )
                                            }
                                        >
                                            <span style={{ display: 'block' }}>
                                                请点击
                                                <If
                                                    condition={authHelper.checkCode(
                                                        'finance:salary:computation:setting:salarytemp:importonetemp'
                                                    )}
                                                >
                                                    【
                                                    <Button
                                                        onClick={() =>
                                                            goToTemplateLibrary(
                                                                monthData,
                                                                currentOrgCode,
                                                                currentSelectYear
                                                            )
                                                        }
                                                        className={cn('text-btn', salaryManageStyle.iconBtn)}
                                                        disabled={simplePageVo.disable || monthData.disable}
                                                    >
                                                        <i className={cn(['iconfont', 'iconlsit_goto-icon'])} />
                                                        引入模板
                                                    </Button>
                                                    】或
                                                </If>
                                                <If
                                                    condition={authHelper.checkCode(
                                                        'finance:salary:computation:setting:salarytemp:edittemp'
                                                    )}
                                                >
                                                    【
                                                    <Button
                                                        onClick={() =>
                                                            onEdit(
                                                                monthData,
                                                                currentOrgCode,
                                                                currentSelectYear
                                                            )
                                                        }
                                                        className={cn('text-btn', salaryManageStyle.iconBtn)}
                                                        disabled={simplePageVo.disable || monthData.disable}
                                                    >
                                                        <i
                                                            className={cn([
                                                                'iconfont',
                                                                'iconlistfunction_edit_icon_default',
                                                                'iconfont-larger'
                                                            ])}
                                                        />
                                                        编辑
                                                    </Button>
                                                    】
                                                </If>
                                                进行配置
                                            </span>
                                        </If>
                                    </span>
                                }
                            />
                        )}
                    </div>
                ))}
            </div>
            <If condition={editModalVisible}>
                <SalaryTemplateModal
                    visible={editModalVisible}
                    organizationCode={editRef.current?.organizationCode}
                    currentYear={editRef.current?.currentYear}
                    currentMonth={editRef.current?.currentMonth}
                    templateId={editRef.current?.templateId}
                    onOk={() => {
                        afterEdit();
                        setEditModalVisible(false);
                    }}
                    onCancel={() => setEditModalVisible(false)}
                />
            </If>
        </div>
    );
};

export default MonthSalaryMain;
